//
//  AppContext.swift
//  Exchange
//
//  Created by rui on 2018/6/11.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class AppContext: NSObject {
    
    static let `default`: AppContext = AppContext()
    
    typealias CoinCallBack = ([TradeCoinModel])->()
    typealias legalCallBack = ([TradeCoinModel])->()
    private var coinDataCallBack: CoinCallBack?
    private var legalDataCallBack: legalCallBack?
    
    lazy var viewModel: AppViewModel = {
        let vm = AppViewModel()
        vm.response = {[weak self](state,isSuccess,errorMsg)in
            if state == ResponseState.trade_coin  {
                if isSuccess {
                    self?.coinCallBack()
                }else {
                    self?.coinCallBack()
                    if let msg = errorMsg {
                        CYMBShow.showMessage(msg)
                    }else {
                        CYMBShow.showMessage(kText("当前无网络,请检查网络"))
                    }
                }
            }else if state == ResponseState.coin_coin {
                if isSuccess {
                    self?.coinCallBack(isCoinBool: true)
                }else {
                    self?.coinCallBack(isCoinBool: true)
                    if let msg = errorMsg {
                        CYMBShow.showMessage(msg)
                    }else {
                        CYMBShow.showMessage(kText("当前无网络,请检查网络"))
                    }
                }
                
            }else if state == ResponseState.home_update_info {
                self?.showUpdateAlert()
            }
        }
        return vm
    }()
    
    var exTickData: [[String:Any]]?
    
    var rate: Double {
        if let json = EXFileManager.default.read(from: EXFileManager.Paths.exRatePath)?.jsonObject as? [String:Any] {
            if let rt = json[AppCacheInfo.default.currency] as? Double {
                return rt
            }
        }
        return 0
    }
    
    override init() {
        super.init()
        //核实版本更新
        viewModel.loadUpdateVersion()
        EXFileManager.default.readAsync(form: EXFileManager.Paths.exTickPath) { (data) in
            self.exTickData = data?.jsonObject as? [[String:Any]]
        }
        NotificationCenter.default.addObserver(self, selector: #selector(weakUp), name: .UIApplicationWillEnterForeground, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(write), name: .UIApplicationDidEnterBackground, object: nil)
    }
    
    @objc func write() {
        if let jsonData = exTickData?.jsonData {
            EXFileManager.default.writeAsync(data: jsonData, to: .exTickPath) { (flag) in
                
            }
        }
    }
    
    ///app重新启动时，刷新一些本地数据
    func refreshLocalData() {
        self.viewModel.loadTradeCoin(resfresh: true)
        self.viewModel.loadCoin(resfresh: true)
    }
    ///获取法币交易支持的币种
    func getTradeCoins(isRefresh:Bool = false,callBack: @escaping CoinCallBack) {
        self.legalDataCallBack = callBack
        self.viewModel.loadTradeCoin(resfresh: isRefresh)
    }
    ///获取币币支持的币种
    func getCoinKind(isRefresh:Bool = false,callBack: @escaping CoinCallBack) {
        
        self.coinDataCallBack = callBack
        self.viewModel.loadCoin(resfresh:isRefresh)
    }
    
    
    ///根据币种代码获取法币的配置信息
    func loadTradeCoinPrecision(coinCode: String) -> TradeCoinModel? {
        var tradeCoin = TradeCoinModel()
        for model in self.viewModel.dataArray {
            if model.coinCode?.lowercased() == coinCode.lowercased() {
                tradeCoin = model
                break
            }
        }
        return tradeCoin
    }
    
    ///根据币种代码获取币币的配置信息
    func loadCoinPrecision(coinCode: String) -> TradeCoinModel? {
        var coin = TradeCoinModel()
        for model in self.viewModel.coinArray {
            if model.coinCode?.lowercased() == coinCode.lowercased() {
                coin = model
                break
            }
        }
        return coin
    }

    @objc func weakUp() {
        viewModel.loadUpdateVersion()
    }
    
    ///获取数字货币的法币的价格 symbol数字货币名称，currency名称，默认取当前法币
    func getExTick(symbol: String,currency: String =  AppCacheInfo.default.currency) -> Double  {
        if let exTick = self.exTickData {
            let datas = exTick.filter { (data) -> Bool in
                return data["money"] as? String == currency
            }
            if let data = datas.first,let symbols = data["symbols"] as? [String:Double]  {
                if let exPrice = symbols[symbol] {
                    return exPrice
                }
            }
        }
        return 0
    }
}

extension AppContext {
    
    func coinCallBack(isCoinBool:Bool = false) {
        DispatchQueue.main.async {
            if isCoinBool == true {
              self.coinDataCallBack?(self.viewModel.coinArray)
            }else {
            self.legalDataCallBack?(self.viewModel.dataArray)
            }
        }
    }
    
    /// 获取币币对法币的价格
    ///
    /// - Parameters:
    ///   - coinKind: 币币名称
    ///   - legalKind: 法币名称
    /// - Returns: 价格
    func archiveLegalPrice(coinKind:String, legalKind:String) -> String {
        let index = coinKind == "CNY" ? 1 : 0
        guard let dic:[String:Any] = self.exTickData?[index]["symbols"]! as? [String : Any] else {
            return "0"
        }
        guard let price = dic[legalKind] as? Double else {
            return "0"
        }
        return String(format: "%.2f", price)
    }
    
    ///显示版本更新信息
    func showUpdateAlert() {
        if viewModel.updateInfo.count <= 0 {
            return
        }
        let dict = viewModel.updateInfo
        ///强制更新的最低版本
        let forceUpdate = dict["forceUpdate"] as? String
        ///当前服务器最新版本
        let newestVersion = dict["newestVersion"] as? String
        
        ///当前本地版本
        let localVersion = UIDevice.current.appVersion
  
        ///是否有新版本
        let isNewVersion = localVersion.compare(newestVersion ?? "") == .orderedAscending
        
        if isNewVersion == false {
            return
        }
        
        ///是否强制更新
        let isForce = localVersion.compare(forceUpdate ?? "") != .orderedDescending
    
        let msg = dict["versionDesc"] as? String
        
        let alertVc = UpgradeAlert(describe: msg ?? "", verson: newestVersion ?? "",isUpgradeBool:isForce)
        
        let urlStr = dict["url"] as? String

        alertVc.downBlock = {
            if let url = URL(string: urlStr ?? ""),UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.openURL(url)
            }
        }
        
        alertVc.cancelBlock = {
            
        }
        
    }
    
}


